package com.meixiang.activity.moments;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.dialog.GiveUpDialogFragment;
import com.meixiang.dialog.SelectDialog;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.main.MXApplication;
import com.meixiang.main.MainActivity;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbStrUtil;
import com.meixiang.view.ClearEditText;
import com.meixiang.view.photoSelectActivity.activity.PhotoFileActivity;
import com.meixiang.view.photoSelectActivity.activity.PhotoListShowActivity;
import com.meixiang.view.photoSelectActivity.util.Bimp;
import com.meixiang.view.photoSelectActivity.util.FileUtils;
import com.meixiang.view.photoSelectActivity.util.ImageItem;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 作者：黑哥 on 2016/5/6 17:53
 * <p/>
 * 内容编辑
 */
public class ContentEditingActivity extends BaseActivity {
    private static final String TAG = "ContentEditingActivity";

    //图像列表
    @Bind(R.id.gridview)
    GridView mGridview;
    @Bind(R.id.tv_moment_publish)
    TextView mTvMomentPublish;
    private Activity mActivity;
    @Bind(R.id.tv_editing_text)
    ClearEditText mTvEditingText;
    @Bind(R.id.tv_editing_text_number)
    TextView mTvEditingTextNumber;
    @Bind(R.id.tv_image_number)
    TextView mTvImageNumber;

    private boolean isInputText = false;
    private boolean isIncludingImage = false;
    private List<File> files = new ArrayList<>();
    private int imageSize;

    private static final int REQUEST_ALL_CODE = 0;
    private static final int WRITE_EXTERNAL_STORAGE = 2;

    public static Bitmap bimap;
    private static final int PHOTO_GRAPH = 0x01;//拍照
    private static final int CROP_IMAGE = 0x04; // 裁剪图片
    private Uri photoUri;

    public static ArrayList<ImageItem> dataList;

    /**
     * 用Gridview
     * <p/>
     * 加载选择中的图片
     * 总共显示9张
     * 当前选中的图片每行显示4张，如果显示的图片
     **/
    private GridAdapter adapter;
    //是否已经添加图片
    private boolean isAddImagaPath = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_content_editing);
        mActivity = ContentEditingActivity.this;
        MXApplication.mApp.AddActivity(mActivity);
        ButterKnife.bind(this);
        bimap = BitmapFactory.decodeResource(
                getResources(),
                R.mipmap.icon_add_pic);

        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initTitle() {
        setTitle("内容编辑", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //当内容不为空时提示保存，否则直接退出
                if (!AbStrUtil.isEmpty(mTvEditingText.getText().toString())) {
                    GiveUpDialogFragment.getIntanceDialog().show(getSupportFragmentManager(), GiveUpDialogFragment.TAG);
                } else {
                    finish();


                }
            }
        });
    }

    @Override
    protected void initView() {
        mTvMomentPublish.setOnClickListener(this);
        mGridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        adapter = new GridAdapter(this);
        mGridview.setAdapter(adapter);
        mGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                /**6.0权限*/

                if (arg2 == Bimp.tempSelectBitmap.size()) {

                    imageSelect();
                } else {
                    Intent intent = new Intent(mActivity,
                            PhotoListShowActivity.class);
                    intent.putExtra("position", "1");
                    intent.putExtra("ID", arg2);
                    startActivity(intent);
                    finish();
                }
            }
        });
        //输入文字的监听事件
        mTvEditingText.addTextChangedListener(new TextWatcher() {
            //之前
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            //之后
            @Override
            public void afterTextChanged(Editable s) {
                //获取当前输入的长度
                mTvEditingTextNumber.setText(mTvEditingText.length() + "/300");

            }
        });

    }

    @Override
    protected void setData() {
        if (!AbStrUtil.isEmpty(MXApplication.mApp.getSession().get("save"))) {
            mTvEditingText.setText(MXApplication.mApp.getSession().get("save"));
            mTvEditingText.setSelection(MXApplication.mApp.getSession().get("save").length());
        }
    }

    @Override
    public void onClick(View v) {
        if (v.equals(mTvMomentPublish)) {
            if ((Tool.isBlank(mTvEditingText.getText().toString()) && mTvEditingText.getText().length() == 0) && Bimp.tempSelectBitmap.size() == 0) {
                Tool.showTextToast(mActivity, "请填写发布内容");
                isInputText = true;
                return;
            }
//            if (Bimp.tempSelectBitmap.size() == 0) {
//                Tool.showTextToast(mActivity, "请填写发布内容");
//                isIncludingImage=true;
//                return;
//            }
//            if(isInputText==false||isIncludingImage==false){
            doPublish();
//            }

        }
    }

    /**
     * 创建一个方法对相片就行选择
     */
    private void imageSelect() {
        new SelectDialog(this, new String[]{"拍照上传", "相册选择"}, new SelectDialog.IResultListener() {
            @Override
            public void SelectResult(int result) {
                if (result == 0) {
                    getCameraPermissions();
                } else {
                    getSDkPermissions();
                }
            }


        });
    }


    private void getCameraPermissions() {
        boolean cameraPermissions = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
        boolean storagePermissions = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        if (Build.VERSION.SDK_INT < 23 || cameraPermissions && storagePermissions) {
            requestCapture();
        } else {
            List<String> permissions = new ArrayList<>();
            if (!cameraPermissions) {
                permissions.add(Manifest.permission.CAMERA);
            }
            if (!storagePermissions) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            String[] requestPermissions = new String[permissions.size()];

            ActivityCompat.requestPermissions(this, permissions.toArray(requestPermissions), REQUEST_ALL_CODE);

        }

    }

    private void getSDkPermissions() {
        boolean storagePermissions = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        if (Build.VERSION.SDK_INT < 23 || storagePermissions) {
            LocalImage();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_ALL_CODE:
                if (grantResults.length > 0) {
                    boolean isRequestOk = false;
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                            isRequestOk = true;
                        } else if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                            isRequestOk = false;
                            // 没有选中 取消权限
                            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])) {
                                //ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA},REQUEST_CODE_CAMERA);
                                // 选中 取消权限
                            } else {
                                showAlertDialog("为了能正常上传图片,请开启相机权限与储存权限", "取消", "手动授权", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Uri uri = Uri.parse("package:" + getPackageName());//包名，指定该应用"com.yingke.teyi"
                                        Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS", uri);
                                        startActivity(intent);
                                    }
                                });
                            }
                            break;
                        }
                    }
                    if (isRequestOk) {
                        requestCapture();
                    }

                }
                break;

            case WRITE_EXTERNAL_STORAGE:

                if (grantResults.length > 0) {
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        LocalImage();
                    } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            //ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA},REQUEST_CODE_CAMERA);

                        } else {
                            showAlertDialog("为了能正常上传图片,请开启储存权限", "取消", "手动授权", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Uri uri = Uri.parse("package:" + getPackageName());//包名，指定该应用"com.yingke.teyi"
                                    Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS", uri);
                                    startActivity(intent);
                                }
                            });
                        }
                    }
                }
                break;
        }

    }


    /**
     * 图片文件选择
     */

    private void LocalImage() {

        Intent intent = new Intent(mActivity,
                PhotoFileActivity.class);
        startActivity(intent);
        finish();

    }

    public class GridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private int selectedPosition = -1;
        private boolean shape;

        public boolean isShape() {
            return shape;
        }

        public void setShape(boolean shape) {
            this.shape = shape;
        }

        public GridAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        public void update() {
            loading();
        }

        public int getCount() {
            if (Bimp.tempSelectBitmap.size() == 8) {
                return 8;
            }
            return (Bimp.tempSelectBitmap.size() + 1);
        }

        public Object getItem(int arg0) {
            return null;
        }

        public long getItemId(int arg0) {
            return 0;
        }

        public void setSelectedPosition(int position) {
            selectedPosition = position;
        }

        public int getSelectedPosition() {
            return selectedPosition;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_gridview,
                        parent, false);
                holder = new ViewHolder();
                holder.image = (ImageView) convertView
                        .findViewById(R.id.item_grid_image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (position == Bimp.tempSelectBitmap.size()) {
                holder.image.setImageBitmap(BitmapFactory.decodeResource(
                        getResources(), R.mipmap.icon_add_pic));
                if (position == 9) {
                    holder.image.setVisibility(View.GONE);
                }
            } else {
                holder.image.setImageBitmap(Bimp.tempSelectBitmap.get(position).getBitmap());
                imageSize = Bimp.tempSelectBitmap.size();
                mTvImageNumber.setText(imageSize + "/" + "8");

                if (isAddImagaPath == false || Bimp.tempSelectBitmap.get(position).getImagePath().contains("meixiang_photos")) {
                    holder.image.setTag(Bimp.tempSelectBitmap.get(position).getImagePath());

                    isAddImagaPath = true;
                } else {
                    holder.image.setTag(Bimp.tempSelectBitmap.get(position).getImagePath());
                }

            }

            return convertView;
        }

        public class ViewHolder {
            public ImageView image;

        }

        Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        adapter.notifyDataSetChanged();
                        break;
                }
                super.handleMessage(msg);
            }
        };

        public void loading() {
            new Thread(new Runnable() {
                public void run() {
                    while (true) {
                        if (Bimp.max == Bimp.tempSelectBitmap.size()) {
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                            break;
                        } else {
                            Bimp.max += 1;
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                        }
                    }
                }
            }).start();
        }
    }


    public void getFile() {
        int imageNum;

        if (mGridview.getCount() == 8) {
            imageNum = mGridview.getCount();
        } else {
            imageNum = mGridview.getCount() - 1;
        }
        for (int i = 0; i < imageNum; i++) {
            ImageView imageView = (ImageView) mGridview.getChildAt(i).findViewById(R.id.item_grid_image);
            Log.e("imageView", i + "-----" + imageView.getTag());
            if (imageView.getTag() != null) {
                String url = (String) imageView.getTag();
                files.add(new File(url));
            }
        }


    }

    //发标
    private void doPublish() {
        getFile();
        HttpParams params = new HttpParams();
        params.put("comment", mTvEditingText.getText().toString().trim());
        Log.e("LW", "输出图片信息=" + files);

        /**
         * 注意:此地方有个bug
         * ohhttp 在上传文件的时间 必须要上传文件格式内容，不能够穿空的对象过去.不然后会报错：NotFindFile
         * 此时为了解决这个问题 你传一个文件格式的文件过去.
         * */
        HttpUtils.postFiles(Config.MOMENTS_PUBLISH_EDIT, params,"commentImages",files, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Log.e("TAG", "打印返回信息===" + result.toString());
                Tool.showTextToast(mActivity, message);
                //发布成功,清空保存草稿
                mTvEditingText.setText("");
                MXApplication.mApp.getSession().set("save", mTvEditingText.getText().toString());
                finish();
               /* //清空数据
                Bimp.tempSelectBitmap.clear();
                adapter.notifyDataSetChanged();
                mTvEditingText.setText("");*/
                Bimp.tempSelectBitmap.clear();
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(mActivity, message);
            }
        });

    }

    @Override
    public void finish() {
        super.finish();
        //当内容不为空时提示保存，否则直接退出
        if (AbStrUtil.isEmpty(mTvEditingText.getText().toString())) {
            MXApplication.mApp.getSession().set("save", "");
        } else {
            MXApplication.mApp.getSession().set("save", mTvEditingText.getText().toString());
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //当内容不为空时提示保存，否则直接退出
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!AbStrUtil.isEmpty(mTvEditingText.getText().toString())) {
                GiveUpDialogFragment.getIntanceDialog().show(getSupportFragmentManager(), GiveUpDialogFragment.TAG);
            } else {
                finish();
            }
        }
        return true;
    }

    /**
     * 调用拍照
     */
    public void requestCapture() {
        Intent openFileIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        openFileIntent.putExtra(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        String filename = "temp";
        ContentValues values = new ContentValues();
        values.put(MediaStore.Audio.Media.TITLE, filename);
        photoUri = MXApplication.mApp.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        openFileIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        startActivityForResult(openFileIntent, PHOTO_GRAPH);
    }

    /**
     * 根据图库图片uri发送图片
     *
     * @param selectedImage
     */
    private void sendPicByUri(Uri selectedImage) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = MXApplication.mApp.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        String str = "未能找到任何图片";
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            cursor = null;
            if (picturePath == null || picturePath.equals("null")) {
                Toast.makeText(activity, str, Toast.LENGTH_SHORT).show();
                return;
            }
//            files.add(new File(url));
//            files=new File(picturePath);
            Log.e("TAG", "得到拍照的图片==" + picturePath);
            files.add(new File(picturePath));
            doPublish();
//            uploadImage(new File(picturePath));
        } else {
            File file = new File(selectedImage.getPath());
            if (!file.exists()) {
                Toast.makeText(activity, str, Toast.LENGTH_SHORT).show();
                return;
            }
            files.add(file);
            doPublish();
//            uploadImage(file);
        }

    }

//    /**
//     * 进入裁剪页面
//     *
//     * @param uri
//     */
//    private void cropImageUri(Uri uri) {
//        Intent intent = new Intent("com.android.camera.action.CROP");
//        intent.setDataAndType(uri, "image/*");
//        intent.putExtra("crop", "true");
//        intent.putExtra("aspectX", "1");
//        intent.putExtra("aspectY", "1");
//        intent.putExtra("outputX", 400);
//        intent.putExtra("outputY", 400);
//        intent.putExtra("scale", true);
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//        intent.putExtra("return-data", false);
//        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//        intent.putExtra("noFaceDetection", true);
//        startActivityForResult(intent, CROP_IMAGE);
//    }

    /**
     * 回调更新数据
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == MainActivity.RESULT_OK) {
            if (requestCode == PHOTO_GRAPH) {
                Uri result;
                Log.e("lw", "输出data=" + data);
                if (data != null) {
                    result = data.getData();
                } else {
                    result = photoUri;
                }
                photoUri = result;
//                Bimp.tempSelectBitmap.get(position).getBitmap()

                Log.e("TAG", "输出当前拍照选择后的图片=" + photoUri);
                try {
                    //内存溢出
                    //得到原始图片
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
                    //释放原始图片占用的内存，防止out of memory异常发生
                    Log.e("TAG", "输出当前拍照选择后的图片=" + photoUri);
                    if (Bimp.tempSelectBitmap.size() < 9) {
                        String fileName = String.valueOf(System.currentTimeMillis());
                        Log.e("lw", "输出图片  data=" + data + "-  fileName=" + fileName + "-  bitmap=" + bitmap);
                        FileUtils.saveBitmap(bitmap, fileName);
                        ImageItem takePhoto = new ImageItem();
                        takePhoto.setBitmap(bitmap);
                        Bimp.tempSelectBitmap.add(takePhoto);
                        // 处理得到图片
                        FileOutputStream fileOutputStream = null;
                        try {
                            // 获取 SD 卡根目录
                            String saveDir = Environment.getExternalStorageDirectory() + "/meixiang_photos";
                            // 新建目录
                            File dir = new File(saveDir);
                            if (!dir.exists()) dir.mkdir();
                            // 生成文件名
                            SimpleDateFormat t = new SimpleDateFormat("yyyyMMddssSSS");
                            String filename = "MX" + (t.format(new Date())) + ".jpg";
                            // 新建文件
                            File file = new File(saveDir, filename);
                            // 打开文件输出流
                            fileOutputStream = new FileOutputStream(file);

                            // 生成图片文件
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 30, fileOutputStream);
//                            // 相片的完整路径
                            String imagPath = file.getPath();
                            Log.e("LW", "输出压缩后的图片路径=" + imagPath);
                            takePhoto.setImagePath(imagPath);
                            adapter.notifyDataSetChanged();
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            if (fileOutputStream != null) {
                                try {
                                    fileOutputStream.close();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }


                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } else if (requestCode == CROP_IMAGE) {
                if (photoUri != null) {
                    sendPicByUri(photoUri);
                } else {
                    Toast.makeText(activity, "照片获取失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HttpUtils.tagCancelRequest(TAG);
        Bimp.tempSelectBitmap.clear();
    }
}
